from os import path
import casbin_pymongo_adapter
import casbin

# RBAC with resource roles

def adapter():
    '''
    ## 数据库读取
    '''
    adapter = casbin_pymongo_adapter.Adapter('mongodb://localhost:27017/', "lumos")
    e = casbin.Enforcer(path.join(path.dirname(__file__), "model.conf"), adapter, True)
    
    adapter.add_policy(sec="p", ptype="p", rule=("alice", "data1", "write"))
    adapter.add_policy(sec="p", ptype="p", rule=("alice", "data1", "read"))
    adapter.add_policy(sec="p", ptype="p", rule=("bob", "data2", "read"))
    adapter.add_policy(sec="p", ptype="p", rule=("data_group_admin", "data_group", "write"))
    adapter.add_policy(sec="g", ptype="g", rule=("alice", "data_group_admin"))
    adapter.add_policy(sec="g", ptype="g2", rule=("data2", "data_group"))
    e.load_policy()
    
    model = e.get_model()
    model.add_policy("p", "p", ["alice", "data1", "read"])
    adapter.save_policy(model)
    
    print(e.get_all_roles())

    sub = "alice"  # the user that wants to access a resource.
    obj = "data1"  # the resource that is going to be accessed.
    act = "read"  # the operation that the user performs on the resource.

    
    if e.enforce(sub, obj, act):
        print('permit alice to read data1')
        pass
    else:
        print('deny the request, show an error')
        pass

def file_adapter():
    '''
    数据库读取  
    policy.csv 最好从数据库读取  
    model.conf 从配置中心加载  
    '''

    e = casbin.Enforcer(path.join(path.dirname(__file__), "model.conf"), 
        path.join(path.dirname(__file__), "policy.csv"))
    sub = "alice"  # the user that wants to access a resource.
    obj = "data1"  # the resource that is going to be accessed.
    act = "read"  # the operation that the user performs on the resource.

    # 获取用户拥有的所有角色
    roles = e.get_roles_for_user("alice")
    print(roles)

    # 获取拥有此角色的所有用户
    print(e.get_users_for_role("admin"))

    # 获取用户拥有的所有权限
    print(e.get_permissions_for_user("alice"))

    if e.enforce(sub, obj, act):
        print('permit alice to read data1')
        pass
    else:
        print('deny the request, show an error')
        pass
    
if __name__ == "__main__":
    adapter()
